import ImageCompressor from 'image-compressor.js'
import EXIF from 'exif-js'
import { uploadLog } from "@/api/common";

//用于获取url地址？号后面的参数值
window.Request = function(key) {
    var url = window.location.hash.indexOf('?') == -1 ? window.location.search : window.location.hash;
    var getStr = "?" + decodeURI(url).split("?")[1];
    var retValue = (getStr.match(new RegExp("(?:^\\?|&)" + key + "=(.*?)(?=&|$)", 'i')) || ['', null])[1];
    return (retValue == null ? "" : retValue);
};

//用于获取url地址？号后面的参数值
window.Request2 = function(key) {
    var url = window.location.href;
    let index1 = url.indexOf('?');
    let index2 = url.lastIndexOf('?');
    let index3 = url.lastIndexOf('#');


    let getStr = '';
    if (index1 == index2) {
        return (Request(key));
    } else {
        let str1 = url.substring(index1, index3);
        let str2 = url.substring(index2 + 1);

        getStr = str1 + '&' + str2
    }

    console.log('getStr==', getStr)
    var retValue = (getStr.match(new RegExp("(?:^\\?|&)" + key + "=(.*?)(?=&|$)", 'i')) || ['', null])[1];
    return (retValue == null ? "" : retValue);
}

window.getUrlParams = function() {
    var url = window.location.href;
    let index1 = url.indexOf('?');
    let str1 = url.substring(index1+1);
    let paramList = str1.split('&');

    let retV = {};
    for(let i=0;i<paramList.length;i++) {
        let a = paramList[i].split('=');
        retV[a[0]] = a[1];
    }

    return retV;
}

//压缩图片
window.compressImg = function(file) {
    var read = new FileReader();
    read.readAsDataURL(file);
    return new Promise(function(resolve, reject) {
        read.onload = function(e) {
            var img = new Image();
            img.src = e.target.result;
            img.onload = function() {
                //默认按比例压缩
                var w = this.width,
                    h = this.height;
                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var base64;
                // 创建属性节点
                canvas.setAttribute("width", w);
                canvas.setAttribute("height", h);
                ctx.drawImage(this, 0, 0, w, h);
                base64 = canvas.toDataURL(file['type']);
                resolve(base64)
            };
        };
    })
};

//压缩图片
window.compressImgByLib = function(file, size) {
    size = size * 1024
    // var file = fileObj.file;
    var fileSize = file['size'];
    console.log('size ==', size)
    console.log('fileSize ==', fileSize)
    return new Promise(function(resolve, reject) {
        let quality = ((size / fileSize > 1) ? 0.8 : size / fileSize).toFixed(1);

        quality = +quality;
        if (quality === 0) {
            quality = 0.1;
        }

        console.log('quality ==', quality)
        console.log('quality ==', typeof quality)
        var imageCompressor = new ImageCompressor();
        imageCompressor.compress(file, {
            quality: quality, // 字符串压缩功能失效
            maxHeight: 1000,
            maxWidth: 1000,
            success: (res) => { // 压缩成功的回调 Handle the compressed image file.
                console.log('res success')
                resolve(res)
            },
            error: (res) => {
                uploadLog({type:1,content:JSON.stringify(res)}).then((res) => {})
                resolve(file)
            }
        })
    })
}

//对图片旋转处理
window.rotateImg = function(img, direction, canvas) {
    //console.log(img); 
    //最小与最大旋转方向，图片旋转4次后回到原方向  
    var min_step = 0;
    var max_step = 3;
    if (!img)
        return;

    //img的高度和宽度不能在img元素隐藏后获取，否则会出错  
    var height = img.height;
    var width = img.width;

    var step = min_step;

    if (direction == 'right') {
        step++;
        //旋转到原位置，即超过最大值  
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }

    //旋转角度以弧度值为参数  
    var degree = step * 90 * Math.PI / 180;
    var ctx = canvas.getContext('2d');
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0);
            break;
    }
}

//将base64转换为文件对象
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], filename, { type: mime });
}

// 文件对象转base64
window.fileToBase64 = function(obj) {

    return new Promise((resolve, reject) => {
        const image = obj; //获取文件域中选中的图片
        let reader = new FileReader(); //实例化文件读取对象
        reader.readAsDataURL(image); //将文件读取为 DataURL,也就是base64编码
        reader.onload = function(ev) { //文件读取成功完成时触发
            let dataURL = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
            resolve(dataURL);
        }
    })
}

function isAdult(birthday) {
    var today = new Date();
    var nowYear = today.getFullYear();
    var nowMonth = today.getMonth() + 1;
    var nowDate = today.getDate();
    if (nowYear - birthday.getFullYear() < 18) {
        return false; // 未成年
    }
    if (nowYear - birthday.getFullYear() > 18) {
        return true; // 成年
    }
    if (nowYear - birthday.getFullYear() == 18) {
        if (nowMonth == birthday.getMonth()) {
            if (nowDate < birthday.getDate()) {
                return false; // 未成年
            } else {
                return true; // 成年
            }
        } else if (nowMonth < birthday.getMonth()) {
            return false; // 未成年
        } else {
            return true; // 成年
        }
    } else {
        return true; // 成年
    }
}

window.IDCardCheck = function(num) {
    num = num.toUpperCase();
    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        console.log(1234);
    }
    // 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
    // 下面分别分析出生日期和校验位
    var len, re;
    len = num.length;
    if (len == 15) {
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
        var arrSplit = num.match(re);

        // 检查生日日期是否正确
        var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            console.log(2234);
        } else {
            // 将15位身份证转成18位
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            num += arrCh[nTemp % 11];
            if (!isAdult(dtmBirth)) {
                console.log(3234);
                return false;
            }

            return true;
        }
    }
    if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
        var arrSplit = num.match(re);
        // 检查生日日期是否正确
        var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            console.log(6234);
        } else {
            // 检验18位身份证的校验码是否正确。
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[nTemp % 11];
            if (valnum != num.substr(17, 1)) {
                console.log(7234);
                return false;
            }
            if (!isAdult(dtmBirth)) {
                console.log(8234);
                return false;
            }

            return true;
        }
    }
    return false;
}

/**
 * <p> 获取加载图片地址 </p>
 * examples: bg/bg.png
 * @param imgPath: string
 */
export const requireImg = (imgPath) => {
    let imgObj = new URL(`../assets/images/${imgPath}`, import.meta.url);
    // console.log(imgObj)
    console.log(import.meta.url)
    return new URL(`../assets/images/${imgPath}`, 'http://localhost:5173/src/').href;
  };
